package com.heima.search.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.search.dtos.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient client;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = ArticleConstants.ARTICLE_ES_SYNC_QUEUE, durable = "true"),
                    exchange = @Exchange(name = ArticleConstants.ARTICLE_ES_SYNC_TOPIC, type = ExchangeTypes.TOPIC),
                    key = ArticleConstants.ARTICLE_ES_SYNC_ROUTINGKEY
            )
    )
    public void getMessage(String message) {
        //TODO
        //解析消息数据得到文章Dto
        ArticleDto articleDto = JSON.parseObject(message, ArticleDto.class);
        SearchArticleVo searchArticleVo = BeanUtil.toBean(articleDto, SearchArticleVo.class);
        //新增或更新ES数据
        if (articleDto != null) {
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON).id(searchArticleVo.getId().toString());

            try {
                client.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
